package models

import (
	"source-admin-go/pkg/jsontool"
	"source-admin-go/src/config/DataBases"
	"source-admin-go/src/config/Redis"
)

type TokenModel struct {
	IdModel
	UserId         uint   `json:"user_id" gorm:"comment:关联用户表ID"`
	Token          string `json:"token" gorm:"varchar(64);comment:token参数"`
	PeriodValidity uint   `json:"period_validity" gorm:"comment:token有效时间，单位秒;default:10"`
	BaseModel
}

func (t TokenModel) TableName() string {
	return "sy_token"
}

func (t TokenModel) TokenValidation(token string) (*UserModel, error) {
	var err error
	var user UserModel
	if token != "" {
		s := Redis.GetValueByKey(token)
		err = jsontool.JsonStringToStruct(s, &user)
		if user.ID == 0 {
			err = DataBases.DB.Where("token = ?", token).First(&t).Error
			if err != nil {
				return nil, err
			}
			UserModel{}.GetDataById(t.UserId, &user)
			val, _ := jsontool.StructToJsonString(&user)
			_ = Redis.SetKeyValue(token, val, 10)
		}
	}
	return &user, err
}
